/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useEffect, useMemo, useState } from 'react';
import { Button, Col, message, Row, Empty, Timeline, Popconfirm } from 'antd';
import type { DeliveryLogItem, JdkOrderDetail, Operate, PayLog } from '@/services/jdk/order';
import KbCloseOrderModal from '@/components/_pages/jdk/order/components/KbCloseOrderModal/';
import { jdkCancelOrder, getJdkOrderDetail } from '@/services/jdk/order';
import { ProFormSelect } from '@ant-design/pro-form';
import { useSelector } from 'umi';
import type { ConnectState } from '@/models/connect';
import { formatMoney } from '@/utils/utils';
import styles from './index.less';
import { transStatus, formatDistance } from '../../_utils';

type PageProps = {
  orderNo: string;
  goBack: () => void;
};

const BaseInfo: React.FC<{ data: JdkOrderDetail; onReload: () => void; task_order_id: string }> = ({
  data,
  onReload,
  task_order_id,
}) => (
  <div>
    <div className={styles.subTitle}>订单基本信息</div>
    <div className={styles.subText}>
      <div>
        订单状态：{data.order_desc} &nbsp;&nbsp;&nbsp;
        <KbCloseOrderModal task_order_id={task_order_id} onReload={onReload} />
      </div>
      <div>来源：{data.source_name == '快宝' ? '自建' : data.source_name}</div>
      <div>创建时间：{data.created_at}</div>
      <div>是否预约单：{data.booking}</div>
      <div>创建账号：{data.account}</div>
      <div>创建店铺名称：{data.shop_name}</div>
      <div>是否服务商：{data.is_league}</div>
      <div>服务商名称：{data.league_name}</div>
      <div>是否自运力：{data.delivery_type == '0' ? '否' : '是'}</div>
      <div>运力接单平台：{data.delivery_brand_name}</div>
      <div>接单时间：{data.delivery_accept_time}</div>
      <div>订单号：{data.id}</div>
      <div>外卖运单号：{data.source_order_no}</div>
      <div>运力单号：{data.delivery_order_no}</div>
      <div>
        配送费：
        <ul>
          {data.delivery_fee_list && data.delivery_fee_list.length > 0
            ? data.delivery_fee_list.map((item: any) => {
                return (
                  <li key={item.created_at}>
                    {item.created_at}：{formatMoney(item.amount)}元
                  </li>
                );
              })
            : null}
        </ul>
      </div>
      <div>物品信息：{data.good_info}</div>
      <div>收件信息：{data.sh_info}</div>
      <div>店铺信息：{data.shop_info}</div>
      <div>配送距离：{data.distance ? formatDistance(Number(data.distance)) : '--'}</div>
      <div>备注：{data.order_remark}</div>
      <div>
        寄件人信息：{data.sender_address + ' ' + data.sender_name + ' ' + data.sender_phone}
      </div>
    </div>
  </div>
);

const Delivery: React.FC<{
  data: DeliveryLogItem[];
  select: Function;
  onCancel: (params: { delivery_brand: string; order_id: string }) => void;
}> = ({ data, onCancel, select }) => {
  return (
    <div>
      <div className={styles.subTitle}>运力信息</div>
      <div className={styles.subText}>
        {select()}
        {data?.length > 0 ? (
          data.map((val, i) => {
            return (
              <div className={styles.delivery} key={i}>
                <div className={styles.delivery_title}>
                  {val.brand_name}（{val.delivery_type == '0' ? '平台' : '自运力'}）
                </div>
                <div>运力发单账号：{val.delivery_account || '---'}</div>
                <div>运力单号：{val.delivery_no}</div>
                <div>
                  发单时间：{val.create.created_at} {val.create.log_desc}
                </div>
                <div>
                  取消时间：{val.cancel.created_at} {val.cancel.log_desc}
                </div>
                <div>当前状态：{val.status_desc}</div>
                <Row>
                  <Col>回调记录：</Col>
                  <Col style={{ flex: 1 }}>
                    {val?.orderback?.length > 0 ? (
                      <Timeline>
                        {val.orderback.map((item) => (
                          <Timeline.Item key={item.created_at}>
                            {item.created_at} {item.log_desc}
                          </Timeline.Item>
                        ))}
                      </Timeline>
                    ) : (
                      '--'
                    )}
                  </Col>
                </Row>
                <div>
                  操作：{transStatus(val.status)}{' '}
                  {['1', '2', '3', '4'].includes(val?.status?.toString()) ? (
                    <Popconfirm
                      title='确定取消？'
                      onConfirm={() =>
                        onCancel({ delivery_brand: val.delivery_brand, order_id: val.order_id })
                      }
                    >
                      <a>取消</a>
                    </Popconfirm>
                  ) : null}
                </div>
              </div>
            );
          })
        ) : (
          <Empty />
        )}
      </div>
    </div>
  );
};

const OperateRecord: React.FC<{ data: Operate[] }> = ({ data }) => {
  return (
    <div>
      <div className={styles.subTitle}>发单运力操作记录</div>
      <div className={styles.subText}>
        {data.length > 0 ? (
          <Timeline>
            {data.map((val) => (
              <Timeline.Item key={val.id}>
                {val.created_at} {val.info}
              </Timeline.Item>
            ))}
          </Timeline>
        ) : (
          <Empty />
        )}
      </div>
    </div>
  );
};

const PayLogList: React.FC<{ data: PayLog[] }> = ({ data }) => (
  <div>
    <div className={styles.subTitle}>支付信息</div>
    <div className={styles.subText}>
      {data.length > 0 ? (
        <Timeline>
          {data.map((val) => (
            <Timeline.Item key={val.created_at}>
              {val.created_at} {val.desc}
            </Timeline.Item>
          ))}
        </Timeline>
      ) : (
        <Empty />
      )}
    </div>
  </div>
);

const Index: React.FC<PageProps> = ({ orderNo, goBack }) => {
  const [value, setValue] = useState('');
  const { winSize } = useSelector((state: ConnectState) => state.global);

  const [infoData, setInfoData] = useState<{
    delivery_log: DeliveryLogItem[];
    operate: Operate[];
    order: JdkOrderDetail;
    payLog: PayLog[];
    task_order_ids: string[];
    option: any[];
    task_order_id: string;
  }>({
    delivery_log: [],
    operate: [],
    order: {} as JdkOrderDetail,
    payLog: [],
    task_order_ids: [],
    task_order_id: '',
    option: [],
  });

  const colSpan = useMemo(() => {
    switch (winSize) {
      case 'sm':
      case 'xs':
        return 24;
      case 'md':
      case 'lg':
        return 12;
      default:
        return 6;
    }
  }, [winSize]);

  const getDetail = (queryData: { id: string; task_order_id?: string }) => {
    getJdkOrderDetail(queryData).then((res) => {
      const { code, data = {}, msg } = res || {};
      if (code == 0) {
        const { task_order_ids, task_order_id } = data;
        setValue(task_order_id);
        const option = task_order_ids.map((item: any) => ({
          label: item,
          value: item,
        }));
        setInfoData((prevData) => {
          return {
            ...prevData,
            ...data,
            option,
          };
        });
      } else {
        message.error(msg);
      }
    });
  };

  const onReload = () => {
    getDetail({ id: orderNo });
  };

  const handleCancel: (params: { delivery_brand: string; order_id: string }) => void = ({
    delivery_brand,
    order_id,
  }) => {
    jdkCancelOrder({
      delivery_brand,
      order_id,
    }).then((res) => {
      if (res.code == 0) {
        message.success('取消成功');
        onReload();
      } else {
        message.error(res?.msg);
      }
    });
  };

  const handleChange = (value_: string) => {
    setValue(value_);
    getDetail({ id: orderNo, task_order_id: value_ });
  };

  const renderSelect = () => {
    return (
      <ProFormSelect
        label='发单批次'
        className={styles.noStyle}
        options={infoData.option}
        initialValue={infoData.task_order_id}
        fieldProps={{
          value,
          onChange: handleChange,
        }}
      />
    );
  };

  useEffect(() => {
    if (orderNo) {
      getDetail({ id: orderNo });
    }
  }, [orderNo]);

  return (
    <Row>
      <Col className={styles.title} span={24}>
        <Row justify='space-between'>
          <Col className={styles.text}>订单详情</Col>
          <Col>
            <Button type='primary' onClick={goBack}>
              返回上一页
            </Button>
          </Col>
        </Row>
      </Col>
      <Col span={24} className={styles.content}>
        <Row>
          <Col span={colSpan}>
            <BaseInfo
              data={infoData.order}
              task_order_id={infoData.task_order_id}
              onReload={onReload}
            />
          </Col>
          <Col span={colSpan}>
            <Delivery data={infoData.delivery_log} select={renderSelect} onCancel={handleCancel} />
          </Col>
          <Col span={colSpan}>
            <OperateRecord data={infoData.operate} />
          </Col>
          <Col span={colSpan}>
            <PayLogList data={infoData.payLog} />
          </Col>
        </Row>
      </Col>
    </Row>
  );
};

export default Index;
